import { ref, createVNode, unref } from 'vue';
import { AlgoAuthApi } from '../../../api';
import { message, Modal } from 'ant-design-vue';
import { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';
import { InfoCircleFilled, CloseCircleFilled } from '@ant-design/icons-vue';

export const useAlgoAuth = () => {
	interface batchAuthDataType {
		status: number;
		serial: string;
		message: string;
	}
	let singleAuthTimeout: NodeJS.Timeout | null = null;
	const batchAuthData = ref<batchAuthDataType[]>([]);
	const batchAuthVisible = ref<boolean>(false); // 批量授权进度框

	const fileList = ref<any[]>([]);
	const offlineAuthVisible = ref<boolean>(false);
	const offlineAuthLoading = ref<boolean>(false);
	const offlineAuthStatus = ref<boolean>(false);

	const offlineAuthType = ref<number>(1); // 1:单个授权  2:批量授权
	const offlineAuthSn = ref();

	const onlineAuthVisible = ref(false);
	const onlineAuthStatus = ref(false);

	const batchAuthColumns: TsGlobalType.TsTableColumn[] = [
		{ dataIndex: 'boxName', title: '设备名称', width: 100, ellipsis: true },
		{ dataIndex: 'serial', title: 'SN码', width: 187, ellipsis: true },
		{ dataIndex: 'status', title: '状态', width: 100, ellipsis: true },
		{ dataIndex: 'message', title: '原因', ellipsis: true }
	];

	// 重置授权状态、数据
	const resetAuthData = () => {
		fileList.value = [];
		batchAuthData.value = [];
		offlineAuthStatus.value = false;
		onlineAuthStatus.value = false;
	};

	// 选择文件
	const handleChange = (info: any) => {
		if (info.file.name.split('.')[1] !== 'lic') {
			message.error(info.file.name + '文件类型错误');
			throw {
				type: 'verify',
				error: '文件类型错误',
				name: info.file.name
			};
		}
		let resFileList = [...info.fileList];
		resFileList = resFileList.slice(-2);
		resFileList = resFileList.map((file) => {
			if (file.response) {
				file.url = file.response;
			}
			return file;
		});
		fileList.value = resFileList;
	};

	// 模拟上传文件成功
	const customRequest = async (options: UploadRequestOption): Promise<void> => {
		const { file, onProgress, onSuccess } = options;
		console.log('file', file);
		if (typeof onProgress === 'function' && typeof onSuccess === 'function') {
			// eslint-disable-next-line promise/avoid-new
			return new Promise((resolve) => {
				setTimeout(() => {
					onProgress({ percent: 100 });
					onSuccess('');
					resolve();
				}, 100);
			});
		}
	};

	// 批量授权请求
	const batchAuthReq = async (type: string, serial: any, formData?: FormData | undefined) => {
		let res: { code: number; data: { boxSerial: any; status: any; message: any }; message: any };
		if (type === 'online') {
			res = await AlgoAuthApi.onlineAuth(serial);
		} else {
			res = await AlgoAuthApi.offlineAuth(serial, formData, {
				headers: {
					'hide-message': true
				}
			});
		}
		if (res.code === 0) {
			let resSn = res.data.boxSerial;
			batchAuthData.value.forEach((item, index, arr) => {
				if (item.serial === resSn) {
					arr[index].status = res.data.status ? 1 : 2;
					arr[index].message = res.data.message;
				}
			});
		} else {
			batchAuthData.value.forEach((item, index, arr) => {
				if (item.serial === serial) {
					arr[index].status = 2;
					arr[index].message = res.message;
				}
			});
		}
	};

	// 上传文件 确认离线授权
	const confirmOfflineAuth = async () => {
		const formData = new FormData();
		formData.append('file', unref(fileList.value)[0].originFileObj);
		// 单个授权
		if (offlineAuthType.value === 1) {
			offlineAuthLoading.value = true;
			let res = await AlgoAuthApi.offlineAuth(offlineAuthSn.value, formData);
			console.log('授权', res);
			if (res.code === 0) {
				if (!res.data.status) {
					Modal.error({
						content: res.data.message,
						centered: false,
						cancelText: null,
						wrapClassName: 'error-modal',
						bodyStyle: { paddingRight: '24px', paddingBottom: '20px' },
						icon: () => createVNode(CloseCircleFilled, { style: 'color:rgba(186, 59, 41, 1);' }),
						okType: 'default'
					});
					offlineAuthLoading.value = false;
					offlineAuthVisible.value = false;
					return;
				}
				offlineAuthStatus.value = true;
			}
			offlineAuthLoading.value = false;
			return;
		}
		// 批量授权
		if (offlineAuthType.value === 2) {
			offlineAuthVisible.value = false;
			batchAuthVisible.value = true;
			for (let i = 0; i < batchAuthData.value.length; i++) {
				batchAuthReq('offline', batchAuthData.value[i].serial, formData);
			}
			return;
		}
	};

	// 单个授权
	const singleAuth = async (type: string, serial: any) => {
		resetAuthData();
		if (type === 'offline') {
			offlineAuthVisible.value = true;
			offlineAuthType.value = 1;
			offlineAuthSn.value = serial;
			return;
		}

		if (type === 'online') {
			onlineAuthVisible.value = true;
			let res = await AlgoAuthApi.onlineAuth(serial);
			// 响应回来  等待1s 为了loading效果
			singleAuthTimeout = setTimeout(() => {
				if (res.code === 0) {
					if (!res.data.status) {
						Modal.error({
							content: res.data.message,
							centered: false,
							cancelText: null,
							wrapClassName: 'error-modal',
							bodyStyle: { paddingRight: '24px', paddingBottom: '20px' },
							icon: () => createVNode(CloseCircleFilled, { style: 'color:rgba(186, 59, 41, 1);' }),
							okType: 'default'
						});
						onlineAuthVisible.value = false;
						return;
					}
					onlineAuthStatus.value = true;
					return;
				}
				onlineAuthVisible.value = false;
				if (res.code === -18) {
					Modal.error({
						content: res.message,
						centered: false,
						cancelText: null,
						wrapClassName: 'error-modal',
						bodyStyle: { paddingBottom: '20px' },
						icon: () => createVNode(CloseCircleFilled, { style: 'color:rgba(186, 59, 41, 1);' }),
						okType: 'default'
					});
					return;
				}
				Modal.info({
					content: res.message,
					centered: false,
					cancelText: null,
					wrapClassName: 'error-modal',
					bodyStyle: { paddingRight: '24px', paddingBottom: '20px' },
					icon: () => createVNode(InfoCircleFilled, { style: 'color:rgba(61, 127, 233, 1);' }),
					okType: 'default'
				});
			}, 1000);
		}
	};

	// 批量授权
	const batchAuth = async (tableAttr: { data: any[]; selectedKeys: string | any[] }, type: string) => {
		resetAuthData();

		let authList = tableAttr.data
			.filter((item) => tableAttr.selectedKeys.includes(item.id))
			.map((item) => {
				return { boxName: item.boxName, serial: item.serial, status: 0, message: '' };
			});
		batchAuthData.value = authList;

		if (type === 'offline') {
			offlineAuthType.value = 2;
			offlineAuthVisible.value = true;
			return;
		}

		if (type === 'online') {
			batchAuthVisible.value = true;
			for (let i = 0; i < authList.length; i++) {
				batchAuthReq('online', authList[i].serial);
			}
		}
	};

	// 批量授权结果再次确认
	const authComplete = () => {
		offlineAuthVisible.value = false;
		onlineAuthVisible.value = false;
		batchAuthVisible.value = false;
	};

	onUnmounted(() => {
		clearTimeout(singleAuthTimeout as NodeJS.Timeout);
	});
	return {
		offlineAuthVisible,
		offlineAuthLoading,
		offlineAuthStatus,
		fileList,

		onlineAuthVisible,
		onlineAuthStatus,

		batchAuthVisible,

		batchAuthData,
		batchAuthColumns,
		handleChange,
		customRequest,
		confirmOfflineAuth,
		singleAuth,
		batchAuth,
		authComplete
	};
};
